package com.xuz;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.function.Function;

/**
 * @user 65453
 * @date 2024/12/4 21:27
 */
public class Step1Server {
    ServerSocket socketServer;
    Function<String, String> handler;

    public Step1Server(Function<String, String> handler) {
        this.handler = handler;
    }

    public void listen(int port) throws IOException {
        socketServer = new ServerSocket(port);
        while (true) {
            this.accept();
        }
    }

    private void accept() {
        try {
            Socket socket = socketServer.accept();
            System.out.println("A socket created");

            DataInputStream inputStream = new DataInputStream(socket.getInputStream());
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

            StringBuilder requestBuilder = new StringBuilder();
            String line = "";

            while (!(line = bufferedReader.readLine()).isEmpty()) {
                requestBuilder.append(line + "\n");
            }
            String request = requestBuilder.toString();
            System.out.println(request);

            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            String response = this.handler.apply(request);
            bufferedWriter.write(response);
            bufferedWriter.flush();
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) throws IOException {
        Step1Server server = new Step1Server(req -> {
            return "HTTP/1.1 200 ok\n\nGood!\n";
        });
        server.listen(8001);
    }
}
